package category

import (
	"context"
	constans "mall/services/product/rpc/consts"
	"mall/services/product/rpc/internal/domain/bo"
	"mall/services/product/rpc/internal/mapper"

	"mall/services/product/rpc/internal/svc"
	"mall/services/product/rpc/pb"

	"github.com/zeromicro/go-zero/core/logx"
)

type ShopCategoryListDTOLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewShopCategoryListDTOLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ShopCategoryListDTOLogic {
	return &ShopCategoryListDTOLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ShopCategoryListDTOLogic) ShopCategoryListDTO(in *pb.ShopCategoryListDTO) (*pb.ShopCategoryListVO, error) {
	// 1.select list
	categoryMapper := mapper.NewCategoryMapper(l.ctx)
	categoryBO := bo.CategoryBO{ShopId: in.ShopId, CategoryId: in.CategoryId, ParentId: -1}
	selectListCtx, selectCountErr := categoryMapper.SelectListCtx(l.svcCtx.DBEngin, categoryBO)
	if selectCountErr != nil {
		return nil, selectCountErr
	}
	if len(selectListCtx) <= 0 {
		return &pb.ShopCategoryListVO{}, nil
	}
	// 2.loop children node
	var returnArr []*pb.ShopCategoryInfoVO
	for _, v := range selectListCtx {
		vo := &pb.ShopCategoryInfoVO{}
		vo.CategoryId = v.CategoryId
		vo.ShopId = v.ShopId
		vo.ParentId = v.ParentId
		vo.Name = v.Name
		vo.Desc = v.Desc
		vo.Path = v.Path
		vo.Status = int32(v.Status)
		vo.Icon = v.Icon
		vo.ImgUrl = v.ImgUrl
		vo.Level = int32(v.Level)
		vo.Seq = int32(v.Seq)
		l.getCategoryTreeList(categoryMapper, vo)
		returnArr = append(returnArr, vo)
	}
	// 3.return package
	return &pb.ShopCategoryListVO{CategoryArr: returnArr}, nil
}

func (l *ShopCategoryListDTOLogic) getCategoryTreeList(categoryMapper *mapper.CategoryMapper, vo *pb.ShopCategoryInfoVO) {
	categoryBO := bo.CategoryBO{ParentId: vo.CategoryId, NeStatus: constans.Delete}
	selectListCtx, err := categoryMapper.SelectListCtx(l.svcCtx.DBEngin, categoryBO)
	if err != nil {
		return
	}
	if len(selectListCtx) < 1 {
		return
	}
	var categoryArr []*pb.ShopCategoryInfoVO
	for _, v := range selectListCtx {
		categoryVO := new(pb.ShopCategoryInfoVO)
		categoryVO.CategoryId = v.CategoryId
		categoryVO.ShopId = v.ShopId
		categoryVO.ParentId = v.ParentId
		categoryVO.Name = v.Name
		categoryVO.Desc = v.Desc
		categoryVO.Path = v.Path
		categoryVO.Status = int32(v.Status)
		categoryVO.Icon = v.Icon
		categoryVO.ImgUrl = v.ImgUrl
		categoryVO.Level = int32(v.Level)
		categoryVO.Seq = int32(v.Seq)
		categoryArr = append(categoryArr, categoryVO)
		// 递归子节点
		l.getCategoryTreeList(categoryMapper, categoryVO)
		vo.ChildrenArr = categoryArr
	}

}
